package util

import fr.opensagres.poi.xwpf.converter.core.ImageManager
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions
import org.apache.log4j.BasicConfigurator
import org.apache.log4j.LogManager
import org.apache.poi.hwpf.HWPFDocument
import org.apache.poi.hwpf.converter.WordToHtmlConverter
import org.apache.poi.xwpf.usermodel.XWPFDocument
import org.docx4j.Docx4J
import org.docx4j.Docx4jProperties
import org.docx4j.openpackaging.packages.WordprocessingMLPackage
import sun.plugin2.message.Conversation
import java.io.*
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.OutputKeys
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult


object OfficeExcuse {
    private fun writeFile(content:String, fileName: String, encode:String) {
        val bw = BufferedWriter(OutputStreamWriter(FileOutputStream(fileName), encode))
        bw.write(content)
        bw.close()
    }


    /**
     * @param desPath 目标路径，用于存储转化后的html文件
     * @param srcFile 源文件
     */
    fun wordToHtml(desPath:String, srcFile: File): Boolean {
        if (!File(desPath).exists()) {File(desPath).mkdirs()}

        if (File(desPath + srcFile.nameWithoutExtension + ".html").exists()) return false

        if (srcFile.extension == "doc") docToHtml(desPath, srcFile)
        else if (srcFile.extension == "docx") docxToHtml(desPath, srcFile)


        return true
    }

    /**
     * @param desPath 目标路径，用于存储转化后的html文件
     * @param srcFile 源文件
     */
    private fun docToHtml(desPath:String, srcFile: File) {


        val input = FileInputStream(srcFile)
        val hwpfdocument = HWPFDocument(input)
        val wordToHtmlConverter = WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument())
        wordToHtmlConverter.setPicturesManager { _, _, suggestedName, _, _ -> "img/$suggestedName" }
        wordToHtmlConverter.processDocument(hwpfdocument)

        val pics = hwpfdocument.picturesTable.allPictures
        if (pics != null) {
            for (pic in pics) {
                if (!File(desPath + "img/").exists()) File(desPath + "img/").mkdirs()
                pic.writeImageContent(FileOutputStream(desPath + "img/" + pic.suggestFullFileName()))
            }
        }

        val htmlDocument = wordToHtmlConverter.document
        val byteArrayOutputStream = ByteArrayOutputStream()
        val domSource = DOMSource(htmlDocument)
        val streamResult = StreamResult(byteArrayOutputStream)

        val transformer = TransformerFactory.newInstance().newTransformer()
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")
        transformer.setOutputProperty(OutputKeys.INDENT, "yes")
        transformer.setOutputProperty(OutputKeys.METHOD, "html")
        transformer.transform(domSource, streamResult)

        byteArrayOutputStream.close()

        val content = String(byteArrayOutputStream.toByteArray())

        writeFile(content, desPath + "${srcFile.nameWithoutExtension}.html", "UTF-8")
    }


    /**
     * @param desPath 目标路径，用于存储转化后的html文件
     * @param srcFile 源文件
     */
    private fun docxToHtml(desPath:String, srcFile: File) {
        Docx4jProperties.getProperties().setProperty("docx4j.Log4j.Configurator.disabled", "true")
        BasicConfigurator.configure()
        Docx4J.toHTML(
                WordprocessingMLPackage.load(srcFile),
                "$desPath/img",
                "$desPath/img",
                FileOutputStream(desPath + "/${srcFile.nameWithoutExtension}.html"))

    }
}